using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;
using System.Text.RegularExpressions;

namespace Impact.Web.Foundation.Handlers
{

    /// <summary>
    /// Encodes any email addresses with a mix of unicode and cleartext to make it harder
    /// for robots to harvest the address.
    /// </summary>
    public class EmailSpamModule : IHttpModule
    {

        #region IHttpModule Members

        /// <summary>
        /// Dispose
        /// </summary>
        public void Dispose()
        {
            // Nothing to dispose; 
        }

        /// <summary>
        /// Init
        /// </summary>
        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }

        #endregion

        void context_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = sender as HttpApplication;
            if (app.Request.RawUrl.Contains(".aspx") || app.Request.RawUrl.Contains(".ashx"))
            {
                app.Response.Filter = new SpamFilter(app.Response.Filter);
            }
        }

        #region Stream filter

        private class SpamFilter : Stream
        {

            public SpamFilter(Stream sink)
            {
                _sink = sink;
            }

            private Stream _sink;

            #region Properites

            public override bool CanRead
            {
                get { return true; }
            }

            public override bool CanSeek
            {
                get { return true; }
            }

            public override bool CanWrite
            {
                get { return true; }
            }

            public override void Flush()
            {
                _sink.Flush();
            }

            public override long Length
            {
                get { return 0; }
            }

            private long _position;
            public override long Position
            {
                get { return _position; }
                set { _position = value; }
            }

            #endregion

            #region Methods

            public override int Read(byte[] buffer, int offset, int count)
            {
                return _sink.Read(buffer, offset, count);
            }

            public override long Seek(long offset, SeekOrigin origin)
            {
                return _sink.Seek(offset, origin);
            }

            public override void SetLength(long value)
            {
                _sink.SetLength(value);
            }

            public override void Close()
            {
                _sink.Close();
            }

            public override void Write(byte[] buffer, int offset, int count)
            {
                byte[] data = new byte[count];
                Buffer.BlockCopy(buffer, offset, data, 0, count);
                string html = System.Text.Encoding.Default.GetString(buffer);

                html = EncodeEmails(html);

                byte[] outdata = System.Text.Encoding.Default.GetBytes(html);
                _sink.Write(outdata, 0, outdata.GetLength(0));
            }

            private static string EncodeEmails(string html)
            {
                foreach (Match match in _Regex.Matches(html))
                {
                    html = html.Replace(match.Value, Encode(match.Value));
                }
                return html;
            }

            private static Regex _Regex = new Regex("(mailto:|)(\\w+[a-zA-Z0-9.-_]*)@(\\w+).(\\w+)");
            private static Random _Random = new Random();

            private static string Encode(string value)
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < value.Length; i++)
                {
                    if (_Random.Next(2) == 1)
                        sb.AppendFormat("&#{0};", Convert.ToInt32(value[i]));
                    else
                        sb.Append(value[i]);
                }

                return sb.ToString();
            }

            #endregion

        }

        #endregion

    }
}
